<template>
	<div class="session-message-container">
		<div class="header">
			<div>
				<el-button type="primary" :class="recordData.total === 0 ? 'gray-btn' : 'download-btn'" @click="onClickDownload" :disabled="recordData.total === 0 ? true : false">下载</el-button>
			</div>
			<div class="search">
				<el-select v-model="allType" placeholder="全部类型" @change="searchType">
					<el-option v-for="item in options" :key="item" :label="item.label" :value="item.value"> </el-option>
				</el-select>
				<el-input placeholder="请输入关键字搜索" v-model="searchKeyWord">
					<el-button slot="append" icon="el-icon-search" @click="searchContent"></el-button>
				</el-input>
			</div>
		</div>
		<div class="sessionMessage-box" v-for="(item, index) in recordData.list" :key="item.id" :class="index % 2 !== 0 ? 'white' : 'gray'">
			<div class="message-box">
				<div class="tag-box">
					<el-tag class="tag-common color-tts" v-if="item.type === 'text-tts'">TTS</el-tag>
					<el-tag class="tag-common color-asr" type="warning" v-else-if="item.type === 'text-asr'">ASR</el-tag>
					<el-tag class="tag-common color-im" type="success" v-else-if="item.type === 'text'">IM聊天</el-tag>
					<el-tag class="tag-common color-pre" type="danger" v-else-if="item.type === 'text-pre-recorded'">预录制播报</el-tag>
					<el-tag class="tag-common color-ttsSpeck" v-else-if="item.type === 'text-tts-agent'">TTS辅助播报</el-tag>
				</div>
				<div class="user-avatar">
					<el-avatar :size="50" :src="item.fromUserAvatar" v-show="item.fromUserAvatar"></el-avatar>
					<el-avatar :size="50" :src="defaultAgentAvatar" v-show="!item.fromUserAvatar && !item.isRobot && item.role == 'agent'"></el-avatar>
					<el-avatar :size="50" :src="defaultRobotAvatar" v-show="!item.fromUserAvatar && item.isRobot && item.role == 'agent'"></el-avatar>
					<el-avatar :size="50" :src="defaultCustomer" v-show="!item.fromUserAvatar && item.role == 'customer'"></el-avatar>
				</div>
				<div class="msg">
					<span class="agent-name" v-html="item.fromUserName"></span>
					<p class="customer-name" v-if="item.customerRole && item.customerRole !== null">
						<span>&lt;</span>
						<span v-html="item.customerRole" v-if="item.customerRole"></span>
						<span>&gt;</span>
					</p>
					<span class="date" v-html="item.createdAt"></span>
					<div class="picText">
						<div v-if="item.data.type === 'pic'">
							<a class="textPic" :href="item.data.url" v-if="item.data.type === 'pic'" v-html="item.data.name" target="_blank"></a>
							<span v-else-if="item.data === 'silence-msg'">- -</span>
							<span class="text" v-html="item.data" v-else :style="(item.type === 'text-asr' || item.type === 'text-pre-recorded') && item.data === '' ? 'display: none' : ''"></span>
						</div>
						<div v-else-if="item.type === 'link' && item.url">
							<a :href="replaceSerach(item.url)" v-html="item.name" style="color: #6384fe" target="_blank"></a>
						</div>
						<div v-else>
							<a class="textPic" :href="item.data.url" v-if="item.data.type === 'doc'" v-html="item.data.name" target="_blank"></a>
							<span v-else-if="item.data === 'silence-msg'">- -</span>
							<p
								class="data-text"
								v-html="item.data"
								v-else
								:style="(item.type === 'text-asr' || item.type === 'text-pre-recorded') && item.data === '获取播报文稿失败' ? 'display: none' : ''"
							></p>
						</div>
					</div>
					<p v-if="item.type === 'text-asr' && item.data === ''" style="margin-top: -25px">- -</p>
					<p class="text-err" v-if="item.type === 'text-pre-recorded' && item.data === '获取播报文稿失败'" v-html="item.data"> </p>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import { getSessionMessage, downloadSessionMessage } from '@/api/api.js';
import { setOperationLogFuntion, appendToken } from '@/utils/tool.js';
import _ from 'lodash';
import defaultCustomerImg from '@/assets/img/upload/default_customer.png';
import defaultAgentAvatar from '@/assets/img/upload/agent_avatar.png';
import defaultRobotAvatar from '@/assets/img/upload/jiqiren.png';
export default {
	props: {
		sessionId: {
			type: String,
			require: true,
			default: () => ''
		}
	},
	data() {
		return {
			searchKeyWord: '',
			allType: '',
			buisnessData: {
				total: '',
				list: []
			},
			recordData: {
				total: '',
				list: []
			},
			defaultCustomer: defaultCustomerImg,
			defaultAgentAvatar: defaultAgentAvatar,
			defaultRobotAvatar: defaultRobotAvatar,
			options: [
				{ label: '全部类型', value: 'all' },
				{ label: 'ASR', value: 'text-asr' },
				{ label: 'TTS', value: 'text-tts' },
				{ label: 'IM聊天', value: 'text' },
				{ label: '预录制播报', value: 'text-pre-recorded' },
				{ label: 'TTS辅助播报', value: 'text-tts-agent' }
			]
		};
	},
	mounted() {
		this.initSessionMessage()
			.then()
			.catch(error => {
				console.log(error);
				// this.$message.error('获取聊天记录失败！');
			});
	},
	computed: {},
	methods: {

		//关键字搜索
		async searchContent() {
			console.log('searchKeyWord', this.searchKeyWord);
			try {
				await this.initSessionMessage();
				console.log('searchResult', this.recordData);
				if (!this.searchKeyWord && this.allType !== 'all') {
					const data = await this.initSessionMessage();
					console.log(data);
					if (this.allType) {
						this.recordData.list = data.list.filter(item => item.type === this.allType);
					}
					return;
				}
				console.log('searchContent:', this.allType);
				if (this.allType === 'all') {
					await this.initSessionMessage();
					this.searchTypeorInput();
				} else if (this.allType === 'text-tts') {
					this.recordData.list = this.buisnessData.list.filter(item => item.type === 'text-tts');
					this.searchTypeorInput();
				} else if (this.allType === 'text-asr') {
					this.recordData.list = this.buisnessData.list.filter(item => item.type === 'text-asr');
					this.searchTypeorInput();
				} else if (this.allType === 'text') {
					this.recordData.list = this.buisnessData.list.filter(item => item.type === 'text');
					this.searchTypeorInput();
				} else if (this.allType === 'text-pre-recorded') {
					this.recordData.list = this.buisnessData.list.filter(item => item.type === 'text-pre-recorded');
					this.searchTypeorInput();
				} else if (this.allType === 'text-tts-agent') {
					this.recordData.list = this.buisnessData.list.filter(item => item.type === 'text-tts-agent');
					this.searchTypeorInput();
				} else {
					this.searchTypeorInput();
				}
			} catch (error) {
				console.log(error);
				this.$message.error('搜索失败！');
			}
		},
		brightKeyword(val) {
			if (!val) {
				return val;
			}
			let keyword = this.searchKeyWord; //获取输入框输入的内容
			// console.log(val.indexOf(keyword));
			if (val.indexOf(keyword) !== -1) {
				//如果包含的话，就把这个字段中的那一部分进行替换成html字符  padding:auto 2px
				return val.replace(eval('/' + keyword + '/g'), `<text style="color: #6384FE; background: #F0F2F3;">${keyword}</text>`);
			}
			// console.log('brightKeyword', keyword);
			// console.log('val:', val);
			return val;
		},
		// 聊天记录详情初始化
		initSessionMessage() {
			return new Promise((resolve, reject) => {
				getSessionMessage(this.sessionId)
					.then(res => {
						console.log('session message data', res.data);
						this.buisnessData.total = res.data.total;
						this.buisnessData.list = res.data.list.map(item => {
							if (item && item.data && item.data.url) {
								if (_.startsWith(item.data.url, 'http://')) {
									item.data.url = _.replace(item.data.url, 'http', 'https');
								}
								item.data.url = appendToken(item.data.url);
							}

							return {
								fromUserId: item.from.fromUserId,
								fromUserName: item.from.fromUserRole === 'agent' ? '坐席' + item.from.fromUserName : item.from.fromUserName,
								customerRole: item.from.customerRole && item.from.customerRole !== null ? item.from.customerRole : '',
								fromUserAvatar: item.from.fromUserAvatar,
								createdAt: this.$moment(item.createdAt).format('YYYY-MM-DD HH:mm:ss'),
								role: item.from.fromUserRole,
								isRobot: item.from.isRobot,
								data: item.data,
								type: item.type,
								url: item?.type === 'link' && item?.data?.url ? item.data.url : '',
								name: item?.type === 'link' && item?.data?.name ? item.data.name : ''
							};
						});
						this.recordData = JSON.parse(JSON.stringify(this.buisnessData));
						resolve(this.recordData);
					})
					.catch(err => {
						this.$requestApiError(err, () => {
							this.$router.push('/');
						});
						console.log(err);
						reject(err);
					});
			});
		},
		// 下载聊天记录
		onClickDownload() {
			downloadSessionMessage(this.sessionId)
				.then(res => {
					console.log(res);
					let downloadURL = URL.createObjectURL(new Blob([res.data], { type: 'text/plain' }));
					let a = document.createElement('a');
					a.href = downloadURL;
					a.download = `${this.sessionId}`;
					document.body.appendChild(a);
					a.click();
					document.body.removeChild(a);
					URL.revokeObjectURL(downloadURL);
					setOperationLogFuntion({ type: '1', category: 'downloadAndExport', content: '下载聊天记录' });
				})
				.catch(e => {
					console.log('error:', e);
					this.$message.error('下载聊天文件失败！');
				});
		},
		searchType() {
			console.log('allType', this.allType);
			// console.log(this.recordData.list, 'searchRecordByName');
			if (this.allType === 'all') {
				this.initSessionMessage();
			} else if (this.allType === 'text-tts') {
				this.recordData.list = this.buisnessData.list.filter(item => item.type === 'text-tts');
			} else if (this.allType === 'text-asr') {
				this.recordData.list = this.buisnessData.list.filter(item => item.type === 'text-asr');
			} else if (this.allType === 'text') {
				this.recordData.list = this.buisnessData.list.filter(item => item.type === 'text');
			} else if (this.allType === 'text-pre-recorded') {
				this.recordData.list = this.buisnessData.list.filter(item => item.type === 'text-pre-recorded');
			} else if (this.allType === 'text-tts-agent') {
				this.recordData.list = this.buisnessData.list.filter(item => item.type === 'text-tts-agent');
			}
			this.searchContent();
		},
		// 搜索类型和关键字取交集
		searchTypeorInput() {
			let result = [];
			this.recordData.list.map(item => {
				if (
					item.createdAt.indexOf(this.searchKeyWord) !== -1 ||
					item.fromUserName.indexOf(this.searchKeyWord) !== -1 ||
					(typeof item.data === 'string' && item.data.indexOf(this.searchKeyWord) !== -1) ||
					(typeof item.data === 'object' && item.data.name && item.data.name.indexOf(this.searchKeyWord) !== -1) ||
					item.customerRole.indexOf(this.searchKeyWord) !== -1 ||
					item.type.indexOf(this.searchKeyWord) !== -1 ||
					item.url.indexOf(this.searchKeyWord) !== -1 ||
					item.name.indexOf(this.searchKeyWord) !== -1
				) {
					result.push(item);
				}
			});
			result.map(item => {
				item.createdAt = this.brightKeyword(item.createdAt);
				item.fromUserName = this.brightKeyword(item.fromUserName);
				item.fromUserAvatar = this.brightKeyword(item.fromUserAvatar);
				item.data = typeof item.data === 'string' ? this.brightKeyword(item.data) : this.brightKeyword(item.data.name);
				item.customerRole = this.brightKeyword(item.customerRole);
				item.type = this.brightKeyword(item.type);
				item.url = this.brightKeyword(item.url);
				item.name = this.brightKeyword(item.name);
			});
			this.recordData.list = result;
			return result;
		},
		// 搜索链接把<text></text> 替换空
		replaceSerach(url) {
			// console.log(url, 'replaceSerach');
			if (url.indexOf('</text>') !== -1) {
				// console.log(url.replace(/\<(\S*?)[^>]*\>.*?|\<.*? \/\>/g, ''), 'url');
				return url.replace(/\<(\S*?)[^>]*\>.*?|\<.*? \/\>/g, '');
			}
			return url;
		}
	}
};
</script>

<style lang="less" scoped>
.session-message-container {
	padding: 20px;
	.el-input {
		width: 370px;
	}
	.el-select {
		width: 140px;
		margin-right: 20px;
	}
	.header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding-bottom: 16px;
		.download-btn {
			background: #6384fe;
			border-radius: 4px;
			color: #fff;
		}
		.gray-btn {
			background: #e7e7e7;
			border: none;
			color: #fff;
		}
	}
	.search {
		color: #666;
	}
	.keyword {
		background-color: #606266;
		color: #6384fe;
	}
	.sessionMessage-box {
		padding-top: 16px;
		.title {
			padding: 14px;
			background-color: #f7f8f9;
			.buisness-name {
				color: #606266;
				padding-right: 20px;
			}
			.buisness-date {
				color: #8e8e93;
			}
		}
		.message-box {
			display: flex;
			// flex-wrap: wrap;
			align-items: center;
			.tag-box {
				width: 100px;
				text-align: center;
				.tag-common {
					font-size: 12px;
					font-family: PingFang SC;
					font-weight: 500;
					height: 22px;
					line-height: 18px;
					margin: 0 10px;
				}
				.color-tts {
					color: #5642f7;
				}
				.color-asr {
					color: #ffa043;
				}
				.color-im {
					color: #17d570;
				}
				.color-pre {
					color: #ff6899;
				}
				.color-ttsSpeck {
					color: #4282f6;
				}
			}
			.user-avatar {
				padding: 14px 20px;
				.el-avatar {
					width: 100%;
				}
			}
			.msg {
				color: #606266;
				padding-left: 19px;
				font-size: 12px;
				line-height: 18px;
				.agent-name {
					color: #8e8e93;
				}
				.date {
					padding-left: 24px;
					color: #8e8e93;
				}
				.text {
					padding-top: 12px;
					line-height: 28px;
				}
				.textPic {
					padding-top: 12px;
					color: #6384fe;
					// border-bottom: 1px solid #6384fe;
				}
				.picText {
					padding: 20px 0;
				}
				.data-text {
					white-space: normal;
					word-break: break-all;
				}
				.customer-name {
					display: inline-block;
					padding-left: 10px;
					font-size: 12px;
					font-family: PingFang SC;
					font-weight: 400;
					color: #6384fe;
					// margin-top: -5px;
				}
				.text-err {
					font-size: 12px;
					font-family: PingFang SC;
					font-weight: 400;
					color: #ef5753;
					margin-top: -30px;
				}
			}
		}
		hr {
			background: #edf0f2;
			opacity: 0.2;
		}
	}
	.white {
		background-color: #fff;
	}
	.gray {
		background: #f7f8f9;
	}
}
</style>

<style lang="less">
.session-message-container {
	.search {
		.el-input__icon {
			line-height: 100%;
		}
	}
}
.el-avatar > img {
	width: 100%;
}
</style>
